package site.shihuan.helpdesk.auth.service;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import site.shihuan.helpdesk.auth.config.AliOssConfig;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * @description:
 * @author: 周世焕
 * @time: 2020-05-26 23:42
 */
@Service
public class AliYunOss {

    @Autowired
    private OSS ossClient;
    @Autowired
    AliOssConfig ossConfig;

    /**
     * 上传文件
     * @param file
     * @return
     */
    public String upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = getFilePath(fileName);
        ossClient.putObject(ossConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
        Calendar cal = Calendar.getInstance();
        //设置起时间
        cal.setTime(new Date());
        //增加一年
        cal.add(Calendar.YEAR, 10);
        // 获取图片地址(当选择私有读写时需要通过这种方式获取地址)
        // 获取图片地址2 (当选择共有读写时 bucketName+endpoint+objectName 为图片地址)
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + filePath;
    }

    public void delete(String objectName) {
        ossClient.deleteObject(ossConfig.getBucketName(), objectName);
    }


    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "helpdesk/images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/"
                + System.currentTimeMillis()
                + sourceFileName;
    }

    public String getObjectName(String url) {
        url = url.substring(8);
        int i = url.indexOf('/');
        return url.substring(i + 1);
    }
}
